package it.eng.area118.mdocommon.android.ntp;

import it.eng.area118.mdocommon.Ntp;
import it.eng.area118.mdocommon.android.DummyBinder;
import it.eng.area118.mdocommon.android.log.BasicLogger;
import it.eng.area118.mdocommon.android.model.AndroidModelContainer;
import it.eng.area118.mdocommon.android.util.AndroidApplicationContext;
import it.eng.area118.mdocommon.android.util.DateUtils;
import it.eng.area118.mdocommon.android.util.SharedPreferenceUtil;
import it.eng.area118.mdocommon.android.util.StringUtils;
import it.eng.area118.mdocommon.android.util.SystemTime;
import it.eng.area118.mdocommon.ntp.DummyNtpService;
import it.eng.area118.mdocommon.ntp.NTPException;
import it.eng.area118.mdocommon.ntp.NtpSynchListener;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class AndroidNtpService extends Service {

	public final static String TAG = AndroidNtpService.class.getName();

	private Ntp ntpService;

	private Timer ntpTimer;

	private Timer timeTickSeconds;

	private NtpSynchListener listener;

	private boolean synchfirstTime;

	private long lastPause;

	// private Calendar lastCal;

	@Override
	public IBinder onBind(Intent arg0) {
		BasicLogger.writeLog(TAG, "onBind");
		return new DummyBinder();
	}

	public static class NtpSynchStarter {
		public static void start() {
			Intent svc = new Intent(AndroidApplicationContext.getInstance()
					.getApplicationContext(), AndroidNtpService.class);
			svc.setAction("getInfo");
			// activity.startService(svc);
			AndroidApplicationContext.getInstance().getApplicationContext()
					.startService(svc);
			// svc.putExtra(OutputActionConstants.SEND, message);
		}
	}

	@Override
	public void onCreate() {
		ntpService = new DummyNtpService();
		synchfirstTime = true;
		String ntpHost = SharedPreferenceUtil.getSharedPrefsValue("ntp_ip_key",
				"10.4.1.12");
		ntpService.config(ntpHost, 8000, 5000);
		timeTickSeconds = new Timer(true);
		timeTickSeconds.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				Intent i = new Intent(AndroidApplicationContext.getInstance()
						.getApplicationContext(), NtpSynchReceiver.class);
				i.setAction("TICK");
				sendBroadcast(i);
			}
		}, 5000, 1000);
		ntpTimer = new Timer("NtpTimer", true);
		BasicLogger.getLog().info(
				"STARTING NTP SERVICE WITH SERVER HOST: " + ntpHost);
		ntpTimer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				synch();
			}
		}, 0, 60000);
		AndroidApplicationContext.getInstance().putApplicationContextEntry(
				AndroidNtpService.class.toString(), AndroidNtpService.this);
		BasicLogger.getLog().info(
				"STARTED NTP SERVICE WITH SERVER HOST: " + ntpHost);
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		String ntpHost = SharedPreferenceUtil.getSharedPrefsValue("ntp_ip_key",
				"216.119.63.113");

		ntpService.config(ntpHost, 8000, 5000);
		String action = intent.getAction();
		BasicLogger.getLog().info(
				"NTP SERVICE onStartCommand: " + ntpHost + " - " + action);
		if (!StringUtils.isEmpty(action) && action.equals("PAUSE")) {
			lastPause = System.currentTimeMillis();
			timeTickSeconds.cancel();
			ntpTimer.cancel();
		}
		if (!StringUtils.isEmpty(action) && action.equals("RESUME")) {
			/* aggiorno l'offset di pause */
			Timer t = new Timer(true);
			t.schedule(new TimerTask() {

				@Override
				public void run() {
					long now = System.currentTimeMillis();
					long diff = now - lastPause;
					int secs = (int) (diff / 1000);

					Intent i = new Intent(AndroidApplicationContext
							.getInstance().getApplicationContext(),
							NtpSynchReceiver.class);
					i.setAction("RESUME");
					i.putExtra("OFFSET", secs);
					sendBroadcast(i);

				}
			}, 0);
			ntpTimer = new Timer("NtpTimer", true);
			ntpTimer.scheduleAtFixedRate(new TimerTask() {

				@Override
				public void run() {
					synch();
				}
			}, 1000, 60000);
			/* riavvio i tick */
			timeTickSeconds = new Timer(true);
			timeTickSeconds.scheduleAtFixedRate(new TimerTask() {

				@Override
				public void run() {
					Intent i = new Intent(AndroidApplicationContext
							.getInstance().getApplicationContext(),
							NtpSynchReceiver.class);
					i.setAction("TICK");
					sendBroadcast(i);
				}
			}, 3000, 1000);

		}
		return super.onStartCommand(intent, flags, startId);
	}

	protected void synch() {

		try {
			Calendar c = ntpService.getInfo();
			// lastCal = c;
			Intent i = new Intent(AndroidApplicationContext.getInstance()
					.getApplicationContext(), NtpSynchReceiver.class);
			if (synchfirstTime) {
				c.add(Calendar.SECOND, 5);
				synchfirstTime = false;
			}
			i.setAction("SYNCH");
			i.putExtra("SYNCH", c);
			sendBroadcast(i);
		} catch (NTPException e) {
			BasicLogger.getLog().error(
					"Error in AndroidNtpService while synch datum", e);
		}
	}

	@Override
	public void onDestroy() {
		// ntpTimer.purge();
		// ntpTimer.cancel();
		// ntpTimer.purge();
		// ntpTimer = null;
		super.onDestroy();
	}

	public NtpSynchListener getListener() {
		return listener;
	}

	public void setListener(NtpSynchListener listener) {
		this.listener = listener;
	}

}
